package leetcode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @author Retain
 * @date 2021/9/11 19:31
 */
public class JD {
    public static void main(String[] args) throws IOException {
//        q2();
    }

    public static void q2() throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int[] s = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int n = s[0];
        int q = s[1];
        HashMap<Integer, List<Integer>> neededService = new HashMap<>();
        for (int i = 1; i <= n; i++) {
            int[] services = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            ArrayList<Integer> list = new ArrayList<>();
            for (int j = 1; j < services.length; j++) {
                list.add(services[j]);
            }
            neededService.put(i, list);
        }

        int[][] oprations = new int[q][2];
        for (int i = 0; i < q; i++) {
            int[] services = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
            oprations[i] = services;
        }
        Set<Integer> aliveService = new HashSet<>();
        for (int i = 0; i < q; i++) {
            int seq = oprations[i][1];
            if (oprations[i][0] == 1) {
                // 启动服务
                start(aliveService,neededService, neededService.get(seq), seq);
            }else {
                // 关闭服务
                remove(aliveService,neededService, neededService.get(seq), seq);

            }
            System.out.println(aliveService.size());
        }
    }

    public static void start(Set<Integer> aliveService, HashMap<Integer, List<Integer>> neededService,List<Integer> nowServices, int seq) {
        if (!neededService.containsKey(seq) || neededService.get(seq).size() == 0) {
            if (neededService.get(seq).size() == 0) {
                aliveService.add(seq);
            }
            return;
        }
        aliveService.add(seq);
        for (Integer nowService : nowServices) {
            start(aliveService, neededService, neededService.get(nowService), nowService);
        }
    }
    public static void remove(Set<Integer> aliveService, HashMap<Integer, List<Integer>> neededService,List<Integer> nowServices, int seq) {
        if (!neededService.containsKey(seq) || neededService.get(seq).size() == 0) {
            if (neededService.get(seq).size() == 0) {
                aliveService.remove(seq);
            }
            return;
        }
        aliveService.remove(seq);
        for (Integer nowService : nowServices) {
            remove(aliveService, neededService, neededService.get(nowService), nowService);
        }
    }
}
